// pages/set/set.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    level: 0,
    codeArray: [ 5, 5, 5, 2, 100, 100, 100, 100],
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      level: app.globalData.level
    })
    if(wx.getStorageSync('set')){
      console.log(wx.getStorageSync('set'),123132)
      this.setData({
        ...wx.getStorageSync('set'),
      })
    }
  },

  // 滑动切换后请求
  changeFinished(e){
    const index = e.target.dataset.code;
    let codeArray = this.data.codeArray;
    codeArray[index]  = e.detail.value;
    this.setData({
      codeArray
    })
    let code = [46, 11, codeArray[0], codeArray[1], codeArray[2], codeArray[3], codeArray[4], codeArray[5], codeArray[6], codeArray[7]];
    let lastCode = this.sum(code);
    code.push(lastCode);
    console.log(code,'写入')
    this.writeBLE(code)
  },

  //全局调用写入蓝牙
  writeBLE(code) {
    let d = app.globalData;
    let buffer = new ArrayBuffer(11);
    let dataView = new DataView(buffer);
    code.forEach((v, i) => dataView.setUint8(i, v))
    const that = this;
    let setData = {
      codeArray: that.data.codeArray,
    }
    wx.setStorageSync('set', setData)
    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: d.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId: d.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId: d.characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success: (res) => {
        console.log('写入蓝牙成功', res.errMsg);
        // app.Toast('修改成功', 'success')
      },
      fali: (err) => {
        console.log('写入蓝牙失败', err);
        app.Toast('修改失败,请检查蓝牙是否打开！')
      }
    })
  },

  sum(arr) {
   return arr.reduce(function(prev, curr, idx, arr){
      return prev + curr;
    });
  },
  
  // 滑动切换事件
  sliderChange(e) {
    const index = e.target.dataset.code;
    let codeArray = this.data.codeArray;
    codeArray[index]  = e.detail.value;
    this.setData({
      codeArray
    })
  },

})